package com.blackbird.jang.layer;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Typeface;
import android.view.MotionEvent;

import com.blackbird.jang.Globals;
import com.blackbird.jang.MainActivity;
import com.blackbird.jang.R;
import com.blackbird.jang.Utils;
import com.blackbird.jang.model.Block;
import com.blackbird.jang.model.ColorchangeButton;
import com.blackbird.jang.model.ExplodingButton;
import com.blackbird.jang.model.GameMap;
import com.blackbird.jang.model.InterchangeButton;
import com.blackbird.jang.model.ToolButton;
import com.wiyun.engine.actions.Action.Callback;
import com.wiyun.engine.actions.MoveTo;
import com.wiyun.engine.astar.AStarStep;
import com.wiyun.engine.nodes.Director;
import com.wiyun.engine.nodes.Label;
import com.wiyun.engine.nodes.Layer;
import com.wiyun.engine.nodes.Sprite;
import com.wiyun.engine.types.WYPoint;

/**
 * 游戏主体
 * 
 * @author jang
 * 
 */
public class GameLayer extends Layer {

	private static GameLayer instance;

	public static int score = 0;
	Label scoreText;

	ToolButton explodingTool;
	ToolButton interchangeTool;
	ToolButton colorchangeTool;

	// 被选中的棋子
	Block preSelected;
	Block interchangeBlock;

	// 方块当前移动状态
	boolean isMoving;

	// 起点
	float moveX1;
	float moveY1;

	// 终点
	float moveX2;
	float moveY2;

	private GameMap map;

	// 移动轨迹
	ArrayList<AStarStep> movePath;

	public static GameLayer getInstance() {
		if (instance == null) {
			instance = new GameLayer();
		}
		return instance;
	}

	private GameLayer() {

		initView();

		// initScore();

		// // 初始化棋子
		makeRandomBlock(Globals.INITIAL_BLOCKS);

		setTouchEnabled(true);
	}

	/**
	 * 初始化棋盘
	 */
	private void initView() {

		Sprite board = Sprite.make(R.drawable.map);
		board.setScale(MainActivity.SCALE_X, MainActivity.SCALE_Y);
		board.setPosition(MainActivity.WIN_WIDTH / 2,
				MainActivity.WIN_HEIGHT / 2);
		board.setName("board");
		addChild(board);

		interchangeTool = InterchangeButton.make(R.drawable.interchange, 0,
				0, 0, this, "onIntegerchange");
		addChild(interchangeTool);
		explodingTool = ExplodingButton.make(R.drawable.blomb, 0, 0, 0, this,
				"onExploding");
		addChild(explodingTool);

		colorchangeTool = ColorchangeButton.make(R.drawable.colorchange, 0,
				0, 0, this, "onColorchange");
		addChild(colorchangeTool);

		map = GameMap.make(this);
	}

	/*************** 道具动作 ******************/
	public void onIntegerchange() {
		interchangeTool.setSelected(!interchangeTool.isSelected());

		if (interchangeTool.isSelected()) {
			explodingTool.reset();
			colorchangeTool.reset();			
			interchangeTool.sparkle();		
		} else {
			interchangeTool.reset();
		}
	}

	public void onExploding() {
		explodingTool.setSelected(!explodingTool.isSelected());

		if (explodingTool.isSelected()) {
			interchangeTool.reset();
			colorchangeTool.reset();
			explodingTool.sparkle();			
		} else {
			explodingTool.reset();
		}
	}

	public void onColorchange() {
		colorchangeTool.setSelected(!colorchangeTool.isSelected());

		if (colorchangeTool.isSelected()) {
			interchangeTool.reset();
			explodingTool.reset();
			colorchangeTool.sparkle();
		} else {
			colorchangeTool.reset();
		}
	}

	/*********************************/
	private void initScore() {

		// score = getScore();

		scoreText = Label.make(String.valueOf("得分：" + score), 24, "DroidSans",
				Typeface.BOLD, 0);
		// scoreText.setColor(color)
		scoreText.setScale(MainActivity.SCALE_X, MainActivity.SCALE_Y);
		// scoreText.setPosition(85, 780);
		scoreText.setPosition(MainActivity.WIN_WIDTH / 2,
				MainActivity.WIN_HEIGHT / 2);
		addChild(scoreText);
	}

	// private int getScore() {
	// DBHelper dbHelper = new DBHelper(GameLayer.this);
	// return dbHelper.queryScore("default");
	// }

	/**
	 * 随机生成棋子，并布局到棋盘中任意位置
	 * 
	 * @param blocks
	 */
	private void makeRandomBlock(int blocks) {

		for (int i = 0; i < blocks && !map.isFull(); i++) {
			int x;
			int y;

			do {
				x = Utils.makeRandom(Globals.MAP_COLS);
				y = Utils.makeRandom(Globals.MAP_ROWS);
			} while (map.isBlockedAt(x, y));

			// 生成一个随机数，根据随机数生成相应的图形
			int random = Utils.makeRandom(6);
			map.setBlock(x, y, Block.make(random));

			// 生成新棋子时判断周围是否满足消失条件
			// removeContinuousBlocks(x, y);
		}
		// if (.isFull()) {
		// System.out.println("数据模型已满，请重建");
		// }
	}

	@Override
	public boolean wyTouchesEnded(MotionEvent event) {
		if (isMoving) {
			System.out.println(">>>>>>>>>>棋子移动中<<<<<<<<<<");
			return true;
		}

		WYPoint e = Director.getInstance().convertToGL(event.getX(), event.getY());
		if (!GameMap.isInner(e.x, e.y)) {
			return true;
		}

		Block curSelected = map.getBlock(e.x, e.y);			
		System.out.println("点击位置:("+e.x+","+ e.y+")");

		//优先按道具操作
		if(isToolSelected(curSelected)){
			return true;
		}
		
		System.out.println("无道具操作，继续进行");

		/*** 对选择的方块进行理 **/		
		if (curSelected != null) {
			if (preSelected != null) {
				preSelected.reset();
				
				//如果两次选择相同则取消
				if (preSelected == curSelected) {
					preSelected = null;
					return true;
				}
			}			
			preSelected = curSelected;			
			preSelected.sparkle();

			// 起点
			moveX1 = e.x;
			moveY1 = e.y;

			return true;
		}else {			
			if(preSelected == null){				
				return true;
			}
			// 终点
			moveX2 = e.x;
			moveY2 = e.y;

			moveByPath();
			return false;
		}	
	}

	private boolean isToolSelected(Block sprite) {
		System.out.println("判断是否有道具操作");
		
		if (explodingTool.isSelected()) {
			System.out.println("已选择炸弹道具");
			if(sprite != null){
				map.removeBlock(sprite);
				explodingTool.reset();
			}		
			return true;
		}

		/**
		 * 只有当两次选择不同的方块时才移动，
		 * 如果两次选中了同一个方块，则取消所选，重新进行选择;
		 */
		if (interchangeTool.isSelected()) {
			System.out.println("已选择互换道具");
			if(sprite != null){
				if (preSelected == null) {					
					preSelected = sprite;
					preSelected.sparkle();
				} else {
					preSelected.reset();	
					
					if(preSelected != sprite){					
						int preX = preSelected.getPositionIntX();
						int preY = preSelected.getPositionIntY();
						int curX = sprite.getPositionIntX();
						int curY = sprite.getPositionIntY();					
						
						map.removeBlock(sprite);
//						map.setBlock(curX, curY, preSelected);
						
//						map.removeBlock(preSelected);				
//						map.setBlock(preX, preY, curSelected);
//						
//						preSelected = null;
//						curSelected = null;
		
						interchangeTool.reset();
					}
				}				
			}	
			return true;
		}

		/*
		 * 当每次点击的都是同一个方块时变换颜色；
		 * 
		 */
		if (colorchangeTool.isSelected()) {
			System.out.println("已选择变色道具");			
			if(sprite != null){
				if(preSelected == null){
					preSelected = sprite;
					preSelected.sparkle();
				}else if(preSelected == sprite){
					for (int i = 0; i < Block.COLOR.length; i++) {
						if (preSelected.getName().equals(Block.COLOR[i])) {

							int x = preSelected.getPositionIntX();
							int y = preSelected.getPositionIntY();

							map.removeBlock(preSelected);

							int index = (i + 1) % Block.COLOR.length;
							preSelected = Block.make(Block.ICONS[index]);
							map.setBlock(x, y, preSelected);
							preSelected.sparkle();
							break;
						}
					}
				}			
			}
			return true;
		}
		return false;		
	}

	/**
	 * 沿指定路径移动棋子
	 */
	private void moveByPath() {
		isMoving = false;
		preSelected.reset();

		// 找出两点间的路径，是否最近？待确认
		movePath = map.findPath(moveX1, moveY1, moveX2, moveY2);
		if (movePath != null && !movePath.isEmpty()) {
			isMoving = true;
			moveToNext();
		}
	}

	MoveTo move;

	private void moveToNext() {
		if (movePath.isEmpty()) {
			return;
		}

		AStarStep step = movePath.get(movePath.size() - 1);
		move = map.findMoveTo(preSelected, step);

		move.setCallback(callback);
		preSelected.runAction(move);

		movePath.remove(movePath.size() - 1);
	}

	Callback callback = new Callback() {
		public void onStart(int actionPointer) {
			System.out.println("start moving from (" + preSelected.getPositionX()
					+ "," + preSelected.getPositionY() + ")");
			System.out.println("finish moving :" + move.isDone());
		}

		public void onStop(int actionPointer) {
			System.out.println("stop moving at (" + preSelected.getPositionX()
					+ "," + preSelected.getPositionY() + ")");
			// System.out.println("finish moving :"+move.isDone());

			if (isArrived()) {
				System.out.println("终点坐标 (" + moveX2 + "," + moveY2 + ")");			

				preSelected.stopAllActions();
				map.removeBlock(moveX1, moveY1);
				map.setBlock(moveX2, moveY2, preSelected);
				preSelected = null;
				isMoving = false;

				removeNearBy(moveX2, moveY2);
			} else {
				moveToNext();
			}
		}

		public void onUpdate(int actionPointer, float t) {
		}
	};

	private boolean isArrived() {
		return movePath.isEmpty() ? true : false;
	}

	/**
	 * 连续的棋子消失
	 * 
	 * @param x
	 * @param y
	 */
	private void removeNearBy(float x, float y) {

		List<Block> list = map.findNearBy(x, y);

		System.out.println("毗邻的同类方块数=" + list.size());

		if (list.size() >= Globals.CONTINUOUS_BLOCKS) {

			for (Block each : list) {

				map.removeBlock(each);
				// score += Block.SCORE.get(each.getName());
			}

		} else {
			makeRandomBlock(Globals.RECREATE_BLOCKS);
		}
	}
}
